package sfeir.gwt.ergosoom.server.guice;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import sfeir.gwt.ergosoom.client.ClientApi;
import sfeir.gwt.ergosoom.client.model.Person;

import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@Deprecated
public class CachingInterceptor implements MethodInterceptor {

    private static MemcacheService cacheService = MemcacheServiceFactory.getMemcacheService();
    private static UserService userService = UserServiceFactory.getUserService();

    @Override
    public Object invoke(MethodInvocation method) throws Throwable {
        Object result;
        String returnType = method.getMethod().getReturnType().getName();
        if (returnType.equals(Person.class.getName())) {
            Object[] args = method.getArguments();
            if (0 == args.length) {
                if (!userService.isUserLoggedIn())
                    throw new ClientApi.NotLoggedInException();
                else {
                    String email = userService.getCurrentUser().getEmail();
                    if (cacheService.contains(email))
                        return cacheService.get(email);
                    else {
                        result = method.proceed();
                        if (null != result)
                            cacheService.put(email, result);
                        return result;
                    }
                }
            }
            if (args[0] instanceof String && cacheService.contains(args[0]))
                return cacheService.get(args[0]);

            result = method.proceed();
            if (null != result) {
                cacheService.put(args[0], result);
            }
            return result;
        } else {
            if (!userService.isUserLoggedIn())
                throw new ClientApi.NotLoggedInException();
            Object[] args = method.getArguments();
            if (0 < args.length && args[0] instanceof Person) {
                Person p = (Person) args[0];
                cacheService.put(userService.getCurrentUser().getEmail(), p);
//                cacheService.put(p.getAlias(), p);
            }
            result = method.proceed();
        }
        return result;
    }
}
